package com.xdcplus.web.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdcplus.mom.constants.NumberConstant;
import com.xdcplus.mom.enums.ResponseEnum;
import com.xdcplus.exceptions.XdcWebException;

import java.io.IOException;
import java.time.Instant;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;

import com.xdcplus.mom.utils.AuthUtils;
import com.xdcplus.mp.service.impl.BaseServiceImpl;
import com.xdcplus.web.common.pojo.dto.CraftCheckOrderItemsFilterDTO;
import com.xdcplus.web.common.pojo.dto.CraftCheckOrderTargetFilterDTO;
import com.xdcplus.web.common.pojo.entity.CraftCheckOrderItems;
import com.xdcplus.web.common.pojo.entity.ToolProductionLineOpe;
import com.xdcplus.web.common.pojo.entity.ToolProductionLineTool;
import com.xdcplus.web.common.pojo.query.CraftCheckOrderItemsQuery;
import com.xdcplus.web.common.pojo.query.CraftCheckOrderTargetQuery;
import com.xdcplus.web.common.pojo.vo.*;
import com.xdcplus.web.mapper.*;
import com.xdcplus.web.common.pojo.entity.ToolProductionLineMain;
import com.xdcplus.web.common.pojo.dto.ToolProductionLineMainDTO;
import com.xdcplus.web.common.pojo.dto.ToolProductionLineMainFilterDTO;
import com.xdcplus.web.common.pojo.query.ToolProductionLineMainQuery;
import com.xdcplus.web.service.ToolProductionLineOpeService;
import com.xdcplus.web.service.ToolProductionLineToolService;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.xdcplus.core.utils.BeanUtils;
import com.xdcplus.pager.vo.PageVO;
import com.xdcplus.mp.utils.PageableUtils;
import com.xdcplus.mp.utils.PropertyUtils;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.stream.Collectors;
import com.xdcplus.web.service.ToolProductionLineMainService;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;




import javax.tools.Tool;

/**
 * (ToolProductionLineMain)表服务实现类
 *
 * @author Man.Chen
 * @since 2024-12-03 16:38:52
 */
@Slf4j
@Service("toolProductionLineMainService")
public class ToolProductionLineMainServiceImpl extends BaseServiceImpl<ToolProductionLineMainMapper, ToolProductionLineMain, ToolProductionLineMain, ToolProductionLineMainVO> implements ToolProductionLineMainService {

    @Autowired
    protected ToolProductionLineMainMapper toolProductionLineMainMapper;

    @Autowired
    private ToolProductionLineOpeMapper toolProductionLineOpeMapper;

    @Autowired
    private ToolProductionLineToolMapper toolProductionLineToolMapper;

    @Autowired
    private ToolProductionLineMainService toolProductionLineMainService;

    @Autowired
    private ToolProductionLineOpeService toolProductionLineOpeService;

    @Autowired
    private ToolProductionLineToolService toolProductionLineToolService;

    @Autowired
    private CraftCheckOrderTargetMapper craftCheckOrderTargetMapper;

    @Autowired
    private CraftCheckOrderItemsMapper craftCheckOrderItemsMapper;


    private static HashMap<String, String> castMap = new HashMap<>();

    {
        // 化拋車間
        castMap.put("ZR", "制绒");
        castMap.put("PK", "硼扩");
        castMap.put("YH", "氧化");
        castMap.put("BSG", "去BSG");
        castMap.put("JP", "碱抛");
        castMap.put("LPCVD", "LPCVD");
        castMap.put("LK", "磷扩");
        castMap.put("PSG", "去PSG");
        castMap.put("RCA", "RCA");
        castMap.put("ALD", "ALD");
        castMap.put("PECVDZM", "正膜");
        castMap.put("PECVDBM", "背膜");
        castMap.put("SWYS", "丝网印刷");
        castMap.put("CSFX", "测试分选");
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Long saveToolProductionLineMain(ToolProductionLineMainDTO toolProductionLineMainDTO) {

        ToolProductionLineMain toolProductionLineMain = new ToolProductionLineMain();
        BeanUtil.copyProperties(toolProductionLineMainDTO, toolProductionLineMain);
        toolProductionLineMain.setCreateTime(new Timestamp(DateUtil.current()));
        
       this.save(toolProductionLineMain);
       return toolProductionLineMain.getId();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean updateToolProductionLineMain(ToolProductionLineMainDTO toolProductionLineMainDTO) {

        ToolProductionLineMain toolProductionLineMain = this.getById(toolProductionLineMainDTO.getId());
        if (ObjectUtil.isNull(toolProductionLineMain)) {
            log.error("updateToolProductionLineMain() The ToolProductionLineMain does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }

        BeanUtil.copyProperties(toolProductionLineMainDTO, toolProductionLineMain);
        toolProductionLineMain.setUpdateUser(toolProductionLineMainDTO.getUpdatedUser());
        toolProductionLineMain.setUpdateTime(new Timestamp(DateUtil.current()));

        return this.updateById(toolProductionLineMain);
    }

    @Override
    public Boolean saveOrUpdateBatch(List<ToolProductionLineMain> toolProductionLineMainList) {

        toolProductionLineMainList.forEach(toolProductionLineMain -> {
            ToolProductionLineMain toolProductionLineMainParam = new ToolProductionLineMain();
            toolProductionLineMainParam.setId(toolProductionLineMain.getId());
            if (ObjectUtil.isNotNull(toolProductionLineMain.getId())) {
                toolProductionLineMain.setId(toolProductionLineMain.getId());
                toolProductionLineMain.setUpdateTime(new Timestamp(DateUtil.current()));
                LambdaUpdateWrapper<ToolProductionLineMain> lambdaUpdate = Wrappers.lambdaUpdate();
                lambdaUpdate.eq(ToolProductionLineMain::getId, toolProductionLineMain.getId());
                update(toolProductionLineMain, lambdaUpdate);
            } else {
                toolProductionLineMain.setCreateTime(new Timestamp(DateUtil.current()));
                save(toolProductionLineMain);
            }
        });
        return true;
    }

    @Override
    public Boolean saveOrUpdateBatchByDTOList(List<ToolProductionLineMainDTO> toolProductionLineMainDTOList) {

        List<ToolProductionLineMain> toolProductionLineMainList = BeanUtils.copyProperties(toolProductionLineMainDTOList, ToolProductionLineMain.class);
        return saveOrUpdateBatch(toolProductionLineMainList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteToolProductionLineMainLogical(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        ToolProductionLineMain toolProductionLineMain = this.getById(id);

        if (ObjectUtil.isNull(toolProductionLineMain)) {
            log.error("deleteToolProductionLineMain() The ToolProductionLineMain does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }
        return this.removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteToolProductionLineMainByIds(String ids) {
        Assert.notNull(ids, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());
		List<String> idList = Arrays.asList(ids.split(","));
		if(CollectionUtil.isEmpty(idList)){
           throw new XdcWebException(ResponseEnum.ERROR);
       }
		idList.forEach(id->{
			ToolProductionLineMain toolProductionLineMain = this.getById(id);
			if (ObjectUtil.isNull(toolProductionLineMain)) {
				log.error("deleteToolProductionLineMain() The ToolProductionLineMain does not exist or has been deleted");
				throw new XdcWebException(ResponseEnum.ERROR);
			}
		});
		
        return this.removeByIds(idList);
    }

    private List<ToolProductionLineMain> queryToolProductionLineMainList(ToolProductionLineMainFilterDTO toolProductionLineMainFilterDTO) {
        ToolProductionLineMainQuery toolProductionLineMainQuery = BeanUtil.copyProperties(toolProductionLineMainFilterDTO, ToolProductionLineMainQuery.class);

        return toolProductionLineMainMapper.queryToolProductionLineMain(toolProductionLineMainQuery);
    }

    @Override
    public List<ToolProductionLineMainVO> queryToolProductionLineMainVOList(ToolProductionLineMainFilterDTO toolProductionLineMainFilterDTO) {
        return this.objectConversion(queryToolProductionLineMainList(toolProductionLineMainFilterDTO));
    }

    @Override
    public PageVO<ToolProductionLineMainVO> queryToolProductionLineMain(ToolProductionLineMainFilterDTO toolProductionLineMainFilterDTO) {
        PageVO<ToolProductionLineMainVO> pageVO = new PageVO<>();

        if (toolProductionLineMainFilterDTO.getCurrentPage() > NumberConstant.ZERO) {
            PageableUtils.basicPage(toolProductionLineMainFilterDTO.getCurrentPage(), toolProductionLineMainFilterDTO.getPageSize(),
                    toolProductionLineMainFilterDTO.getOrderType(), toolProductionLineMainFilterDTO.getOrderField());
        }

        List<ToolProductionLineMain> toolProductionLineMainList = queryToolProductionLineMainList(toolProductionLineMainFilterDTO);

        PageInfo<ToolProductionLineMain> pageInfo = new PageInfo<>(toolProductionLineMainList);
        PropertyUtils.copyProperties(pageInfo, pageVO, this.objectConversion(toolProductionLineMainList));

        return pageVO;
    }

    @Override
    public ToolProductionLineMainVO queryToolProductionLineMainById(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        return this.objectConversion(this.getById(id));
    }

    //新增研发线
    @Transactional
    @Override
    public Long addProductionLine(ToolProductionLineMainVO productionLineMainVO) {

        // 先判断研发名称是否为空
        if (StringUtils.isEmpty(productionLineMainVO.getLineName())) {
            throw new XdcWebException(ResponseEnum.ERROR, "研发线名称不能为空");
        }
        String lineName = productionLineMainVO.getLineName();
        if (!toolProductionLineMainMapper.findToolProductionLineMainVO(lineName).isEmpty()) {
            throw new XdcWebException(ResponseEnum.ERROR, "该研发线已存在");
        }
        productionLineMainVO.setCreateUser(AuthUtils.getCurrentUser());
        productionLineMainVO.setCreateTime(Timestamp.from(Instant.now()));
        productionLineMainVO.setUpdateUser(AuthUtils.getCurrentUser());
        productionLineMainVO.setUpdateTime(Timestamp.from(Instant.now()));
        productionLineMainVO.setStatus(0L);

        //类型转换
        ToolProductionLineMainDTO toolProductionLineMainDTO =
                BeanUtils.copyProperties(productionLineMainVO, ToolProductionLineMainDTO.class);
        //获取研发线id
        Long mainId = toolProductionLineMainService.saveToolProductionLineMain(toolProductionLineMainDTO);
        addOpesAndTools(mainId, productionLineMainVO.getOpes());
        return mainId;
    }


    //新增工序+线别
    public void addOpesAndTools(Long mainId, List<ToolProductionLineOpeVO> productionLineOpeVOS) {

        //给工序添加研发线id
        List<ToolProductionLineOpeVO> opeList =
                BeanUtils.copyProperties(productionLineOpeVOS, ToolProductionLineOpeVO.class);

        opeList.forEach(ope -> {
            ope.setMainId(mainId);
            ope.setOpeName(castMap.get(ope.getOpeCode()));
        });

        // 将ToolProductionLineOpeVO实体对象转换回ToolProductionLineOpe
        List<ToolProductionLineOpe> toolProductionLineOpeList = BeanUtils.copyProperties(opeList, ToolProductionLineOpe.class);
        // 批量新增工序到数据库并返回所有新增工序id
        List<Long> opeIds = toolProductionLineOpeService.saveOrUpdateBatch(toolProductionLineOpeList);

        // 获取工序新增数据库id
        int size = opeList.size();
        if (size != opeIds.size()) {
            throw new XdcWebException(ResponseEnum.ERROR, "工序id数量不匹配");
        }
        // 批量新增线别
        List<ToolProductionLineTool> toolLists = new ArrayList<>();
        List<String> toolCodes = new ArrayList<>();
        for (ToolProductionLineOpeVO ope : opeList) {
            for (ToolProductionLineToolVO tool : ope.getTools()) {
                toolCodes.add(tool.getToolCode());
            }
        }

        List<ToolProductionToolIfoVO> toolProductionToolIfoVOS = toolProductionLineMainMapper.findToolProductionToolIfoVO(toolCodes);
        Map<String, ToolProductionToolIfoVO> toolInfoMap = toolProductionToolIfoVOS.stream()
                .collect(Collectors.toMap(ToolProductionToolIfoVO::getToolCode, info -> info));

        for (int i = 0; i < opeList.size(); i++) {
            List<ToolProductionLineTool> tools = BeanUtils.copyProperties(opeList.get(i).getTools(), ToolProductionLineTool.class);
            for (ToolProductionLineTool tool : tools) {
                ToolProductionToolIfoVO toolInfo = toolInfoMap.get(tool.getToolCode());
                if (toolInfo != null) {
                    tool.setLineNo(toolInfo.getBayId());
                    tool.setToolName(toolInfo.getToolName());
                }
                tool.setOpeId(opeIds.get(i));
                toolLists.add(tool);
            }
        }

        toolProductionLineToolService.saveOrUpdateBatch(toolLists);
    }

    //查询并返回工序和线别id
    public Map<String, String> queryOpeAndToolId(Long mainId) {

        Map<String, String> map = new HashMap<>();
        StringBuilder opeIds = new StringBuilder();
        StringBuilder toolIds = new StringBuilder();
        List<Long> opeid = toolProductionLineOpeMapper.findIdBymainId(mainId);
        for (int i = 0; i < opeid.size(); i++) {
            long id = opeid.get(i);
            opeIds.append(id);
            if (i < opeid.size() - 1) {
                opeIds.append(",");
            }
        }
        map.put("opeIds", opeIds.toString());
        List<Long> toolid = toolProductionLineToolMapper.findIdByopeId(opeid);
        for (int i = 0; i < toolid.size(); i++) {
            long id = toolid.get(i);
            toolIds.append(id);
            if (i < toolid.size() - 1) {
                toolIds.append(",");
            }
        }
        map.put("toolIds", toolIds.toString());
        return map;
    }


    //查询研发线详细线别
    @Override
    public List<ToolProductionLineMainVO> findProductionLine(ToolProductionLineMainDTO toolProductionLineMainDTO) {
        if (StringUtils.isEmpty(toolProductionLineMainDTO.getMaterialCode())) {
            throw new XdcWebException(ResponseEnum.ERROR, "规格不能为空");
        }
        //查询所有研发线
        List<ToolProductionLineMainVO> toolProductionLineMainVOS = toolProductionLineMainMapper.findProductionLine(toolProductionLineMainDTO);
        // 获取所有研发线id
        List<Long> mainIds = toolProductionLineMainVOS.stream()
                .map(ToolProductionLineMainVO::getId)
                .collect(Collectors.toList());
        // 查询所有工序
        List<ToolProductionLineOpeVO> toolProductionLineOpeVOS = toolProductionLineOpeMapper.findOpesByMainId(mainIds);

        // 获取所有工序id
        List<Long> opeIds = toolProductionLineOpeVOS.stream()
                .map(ToolProductionLineOpeVO::getId)
                .collect(Collectors.toList());

        // 查询所有设备线别
        List<ToolProductionLineToolVO> toolProductionLineToolVOS = toolProductionLineToolMapper.findToolsByOpeId(opeIds);
        // 根据每一条研发线工序对应研发线id分组
        Map<Long, List<ToolProductionLineOpeVO>> opeMap = toolProductionLineOpeVOS.stream()
                .collect(Collectors.groupingBy(ToolProductionLineOpeVO::getMainId));
        //根据每一条研发线设备线别对应工序分组
        Map<Long, List<ToolProductionLineToolVO>> toolMap = toolProductionLineToolVOS.stream()
                .collect(Collectors.groupingBy(ToolProductionLineToolVO::getOpeId));
        //将对应研发线工序根据id添加进研发线
        for (ToolProductionLineMainVO mainVO : toolProductionLineMainVOS) {
            Long mainId = mainVO.getId();
            List<ToolProductionLineOpeVO> opes = opeMap.getOrDefault(mainId, Collections.emptyList());
        //将对应研发线设备线别根据id添加进对应工序
            for (ToolProductionLineOpeVO opeVO : opes) {
                Long opeId = opeVO.getId();
                List<ToolProductionLineToolVO> tools = toolMap.getOrDefault(opeId, Collections.emptyList());
                opeVO.setTools(tools);
            }
            mainVO.setOpes(opes);
        }

       return toolProductionLineMainVOS;

    }
    //修改研发线
    @Transactional
    @Override
    public void updateProductionLineById(ToolProductionLineMainVO productionLineMainVO) {

        if (productionLineMainVO.getId() == null || productionLineMainVO.getLineName() == null) {
            throw new XdcWebException(ResponseEnum.ERROR, "id和研发线名称传入都不能为空");
        }
        Long mainId = productionLineMainVO.getId();
        ToolProductionLineMain toolProductionLineMain = toolProductionLineMainMapper.selectById(mainId);
        if (toolProductionLineMain.getStatus() != 0L) {
            throw new XdcWebException(ResponseEnum.ERROR, "该研发线禁止修改");
        }


        productionLineMainVO.setUpdateUser(AuthUtils.getCurrentUser());
        productionLineMainVO.setUpdateTime(Timestamp.from(Instant.now()));
        //获取该研发线工序和线别所有id
        String opeIDs = queryOpeAndToolId(mainId).get("opeIds");
        String toolIDs = queryOpeAndToolId(mainId).get("toolIds");

        toolProductionLineMainService.updateToolProductionLineMain(BeanUtils.copyProperties(productionLineMainVO, ToolProductionLineMainDTO.class));
        toolProductionLineOpeService.deleteToolProductionLineOpeByIds(opeIDs);
        toolProductionLineToolService.deleteToolProductionLineToolByIds(toolIDs);
        addOpesAndTools(mainId, productionLineMainVO.getOpes());

    }

    //删除研发线
    @Transactional
    @Override
    public void deleteProductionLineById(Long mainId) {

        ToolProductionLineMain toolProductionLineMain = toolProductionLineMainMapper.selectById(mainId);
        if (toolProductionLineMain.getStatus() != 0L) {
            throw new XdcWebException(ResponseEnum.ERROR, "该研发线不能删除");
        }
        toolProductionLineMain.setStatus(-1L);
        toolProductionLineMainService.updateToolProductionLineMain(BeanUtils.copyProperties(toolProductionLineMain, ToolProductionLineMainDTO.class));
    }
    @Transactional
    @Override
    public void updateProductionLineByIdAndStatus(Long mainId, Long status) {
        if(status != -1L && status != 0L && status != 1L){
            throw new XdcWebException(ResponseEnum.ERROR, "状态值不合法");
        }
        ToolProductionLineMain toolProductionLineMain = toolProductionLineMainMapper.selectById(mainId);
        if(toolProductionLineMain == null){
            throw new XdcWebException(ResponseEnum.ERROR, "该研发线不存在");
        }

        toolProductionLineMain.setStatus(status);
        toolProductionLineMainService.updateToolProductionLineMain(BeanUtils.copyProperties(toolProductionLineMain, ToolProductionLineMainDTO.class));
    }
    @Transactional
    @Override
    public List<ToolProductionDataItemVO> queryLineSpcData(Long mainId) {

        ToolProductionLineMain toolProductionLineMain = toolProductionLineMainMapper.selectById(mainId);
        String opeIDs = queryOpeAndToolId(mainId).get("opeIds");
        List<Long> opeList = new ArrayList<>();
        String[] lists = opeIDs.split(",");
        for (String list : lists) {
            opeList.add(Long.parseLong(list));
        }

        //SPC筛选条件
        String startDate = DateUtil.format(toolProductionLineMain.getStartDate(), "yyyy-MM-dd HH:mm:ss");
        String endDate = DateUtil.format(toolProductionLineMain.getEndDate(), "yyyy-MM-dd HH:mm:ss");
        String proSpec = toolProductionLineMain.getMaterialCode();
        List<ToolProductionCodeVO> toolProductionCodeVOList = toolProductionLineOpeMapper.findCodeByOpeId(opeList);


        // 定义opeCode与paramCode的对应关系
        Map<String, List<String>> opeCodeParamCodeMap = new HashMap<>();
        List<String> thicknessList = new ArrayList<>();
        thicknessList.add("thickness");
        opeCodeParamCodeMap.put("ZR", thicknessList);
        opeCodeParamCodeMap.put("JP", thicknessList);
        opeCodeParamCodeMap.put("RCA", thicknessList);

        List<String> difThicknessList = new ArrayList<>();
        difThicknessList.add("dif_thickness");
        opeCodeParamCodeMap.put("PK", difThicknessList);
        opeCodeParamCodeMap.put("LK", difThicknessList);

        List<String> wetWeightList = new ArrayList<>();
        wetWeightList.add("wet_weight1");
        wetWeightList.add("wet_weight2");
        wetWeightList.add("wet_weight3");
        wetWeightList.add("wet_weight4");
        opeCodeParamCodeMap.put("SWYS", wetWeightList);

        // 提取不同opeCode对应的toolCode
        Map<String, List<String>> eqptCodeMap = new HashMap<>();
        for (String opeCode : opeCodeParamCodeMap.keySet()) {
            List<String> eqptCodes = extractToolCodes(toolProductionCodeVOList, opeCode);
            eqptCodeMap.put(opeCode, eqptCodes);
        }

        // 对应关系paramMap，调用不同的接口
        List<Map<String, Object>> paramMaps = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : opeCodeParamCodeMap.entrySet()) {
            String opeCode = entry.getKey();
            List<String> paramCodes = entry.getValue();
            List<String> eqptCodes = eqptCodeMap.get(opeCode);

            if (paramCodes.size() == 1) {
                Map<String, Object> paramMap = buildParamMap(eqptCodes, opeCode, paramCodes.get(0), startDate, endDate, proSpec);
                paramMaps.add(paramMap);
            } else {
                // SWYS对应多个paramCode，为每个paramCode单独构建paramMap
                for (String paramCode : paramCodes) {
                    Map<String, Object> paramMap = buildParamMap(eqptCodes, opeCode, paramCode,startDate, endDate, proSpec);
                    paramMaps.add(paramMap);
                }
            }
        }
        // 调用接口并收集返回结果中的data数据
        String authorization = getAuthorization();
        List<JsonNode> allDataNodes = new ArrayList<>();
        for (Map<String, Object> paramMap : paramMaps) {
            JsonNode result = makeApiCall(paramMap,authorization);
            if (result!= null) {
                allDataNodes.add(result);
            }
        }

        ObjectMapper objectMapper = new ObjectMapper();
        List<ToolProductionDataItemVO> allDataItems = new ArrayList<>();
        for (JsonNode dataNode : allDataNodes) {
            for (int i = 0; i < dataNode.size(); i++) {
                ToolProductionDataItemVO dataItem = null;
                try {
                    dataItem = objectMapper.treeToValue(dataNode.get(i), ToolProductionDataItemVO.class);
                    if("ZR".equals(dataItem.getOpeCode())){
                        dataItem.setName(dataItem.getName()+"控制");
                    }else{
                        dataItem.setName(dataItem.getName().replace("模板","控制"));
                    }

                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                allDataItems.add(dataItem);
            }
        }

        List<String> opeCodeList = Arrays.asList("ZR", "JP", "RCA", "PK", "LK", "SWYS");
        Comparator<ToolProductionDataItemVO> comparator = (item1, item2) -> {
            int opeCodeIndex1 = opeCodeList.indexOf(item1.getOpeCode());
            int opeCodeIndex2 = opeCodeList.indexOf(item2.getOpeCode());

            if (opeCodeIndex1 != opeCodeIndex2) {
                return Integer.compare(opeCodeIndex1, opeCodeIndex2);
            }

            int equipmentNoComparison = item1.getEquipmentNo().compareTo(item2.getEquipmentNo());
            if (equipmentNoComparison != 0) {
                return equipmentNoComparison;
            }
            if ("SWYS".equals(item1.getOpeCode())) {
                return item1.getParamCode().compareTo(item2.getParamCode());
            }
            return 0;
        };

        Collections.sort(allDataItems, comparator);
        System.out.println(allDataItems);
        return allDataItems;
    }
    @Transactional
    @Override
    public List<ToolProductionDataVO> queryLineSpcControlChart(ToolProductionControlVO toolProductionControlVO) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost("http://172.16.34.71/api/spc-service/SPCService/GetAnalysisData");
            post.addHeader("Authorization", getAuthorization());
            post.setHeader("Content-Type", "application/json");
            ToolProductionControlVO productionControlVO = new ToolProductionControlVO();
            productionControlVO.setProjectId(toolProductionControlVO.getProjectId());
            productionControlVO.setStartTime(toolProductionControlVO.getStartTime());
            productionControlVO.setEndTime(toolProductionControlVO.getEndTime());
            productionControlVO.setEqptCodes(toolProductionControlVO.getEqptCodes());
            productionControlVO.setSampleCount(25);
            productionControlVO.setCalcType(2);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonInputString = objectMapper.writeValueAsString(productionControlVO);
            StringEntity entity = new StringEntity(jsonInputString);
            post.setEntity(entity);
            // 发送请求并接收响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    JsonNode rootNode = objectMapper.readTree(responseBody);
                    JsonNode dataNode = rootNode.path("data");
                    List<ToolProductionDataVO> result = new ArrayList<>();
                    // 将JsonNode转换为ToolProductionDataVO对象
                    ToolProductionDataVO toolProductionDataVO = objectMapper.treeToValue(dataNode, ToolProductionDataVO.class);
                    result.add(toolProductionDataVO);
                    return result;
                } else {
                    System.out.println("错误码" + statusCode);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Transactional
    @Override
    public PageVO<CraftCheckOrderTargetVO> queryLineOrderTargetList(Long mainId) {
        PageVO<CraftCheckOrderTargetVO> pageVO = new PageVO<>();

        ToolProductionLineMain toolProductionLineMain = toolProductionLineMainMapper.selectById(mainId);
        String toolIDs = queryOpeAndToolId(mainId).get("toolIds");
        List<Long> longList = new ArrayList<>();
        String[] parts = toolIDs.split(",");
        for (String part : parts) {
            longList.add(Long.parseLong(part));
        }

        //工艺参数筛选条件
        String startDate = DateUtil.format(toolProductionLineMain.getStartDate(), "yyyy-MM-dd HH:mm:ss");
        String endDate = DateUtil.format(toolProductionLineMain.getEndDate(), "yyyy-MM-dd HH:mm:ss");
        List<String> toolCodes = toolProductionLineToolMapper.findNameById(longList);

        CraftCheckOrderTargetFilterDTO craftCheckOrderTargetFilterDTO = new CraftCheckOrderTargetFilterDTO();
        craftCheckOrderTargetFilterDTO.setCheckStartTime(startDate);
        craftCheckOrderTargetFilterDTO.setCheckEndTime(endDate);
        craftCheckOrderTargetFilterDTO.setModeType(2);

        //筛选条件
        CraftCheckOrderTargetQuery craftCheckOrderTargetQuery = BeanUtils.copyProperties(craftCheckOrderTargetFilterDTO, CraftCheckOrderTargetQuery.class);
        List<CraftCheckOrderTargetVO> craftCheckOrderTargetList =
                craftCheckOrderTargetMapper.queryCraftCheckOrderTargetSec(craftCheckOrderTargetQuery);
        List<CraftCheckOrderTargetVO> filteredList = craftCheckOrderTargetList.stream()
                .filter(targetVO -> toolCodes.contains(targetVO.getToolCode()))
                .collect(Collectors.toList());
        PageInfo<CraftCheckOrderTargetVO> pageInfo = new PageInfo<>(filteredList);
        PropertyUtils.copyProperties(pageInfo, pageVO, filteredList);
        return pageVO;
    }

    //查询详细点检数据
    @Transactional
    @Override
    public PageVO<CraftCheckOrderItemsVO> queryLineCraftCheckOrderItems(Long id) {

        PageVO<CraftCheckOrderItemsVO> pageVO = new PageVO<>();

        CraftCheckOrderItemsFilterDTO craftCheckOrderItemsFilterDTO = new CraftCheckOrderItemsFilterDTO();
        craftCheckOrderItemsFilterDTO.setTargetIdFk(id);
        CraftCheckOrderItemsQuery craftCheckOrderItemsQuery = BeanUtil.copyProperties(craftCheckOrderItemsFilterDTO, CraftCheckOrderItemsQuery.class);

        List<CraftCheckOrderItems> craftCheckOrderItemsList =
                craftCheckOrderItemsMapper.queryCraftCheckOrderItems(craftCheckOrderItemsQuery);
        PageInfo<CraftCheckOrderItems> pageInfo = new PageInfo<>(craftCheckOrderItemsList);
        List<CraftCheckOrderItemsVO> craftCheckOrderItemsVOList = BeanUtils.copyProperties(craftCheckOrderItemsList, CraftCheckOrderItemsVO.class);
        PropertyUtils.copyProperties(pageInfo, pageVO, craftCheckOrderItemsVOList);
        return pageVO;


    }
    @Transactional
    @Override
    public ToolProductionDjAndSpcVO queryLineCraftCheckOrderItemsAndSpc(Long id) {
        ToolProductionDjAndSpcVO toolProductionDjAndSpcVO = new ToolProductionDjAndSpcVO();
        toolProductionDjAndSpcVO.setPageVO(queryLineOrderTargetList(id));
        toolProductionDjAndSpcVO.setToolProductionDataList(queryLineSpcData(id));
        return toolProductionDjAndSpcVO;
    }
    @Transactional
    @Override
    public ToolDmIvSummaryVO queryElectricityPerformanceReport(Long id) {


        return null;
    }




    public String getAuthorization(){
        String loginUrl = "http://172.16.34.71/api/permission/basicLogin";
        String json = "{" +
                "\"account\": \"135873\"," +
                "\"password\": \"123456\"" +
                "}";
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);

        Request request = new Request.Builder()
                .url(loginUrl)
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            int statusCode = response.code();
            if (statusCode == 200) {
                // 获取authorization字段的值
                String authorizationValue = response.header("authorization");
                if (authorizationValue!= null) {
                    return authorizationValue;
                } else {
                    System.out.println("未找到authorization字段");
                }
            } else {
                System.out.println("登录请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static List<String> extractToolCodes(List<ToolProductionCodeVO> list, String opeCode) {
        return list.stream()
                .filter(vo -> opeCode.equals(vo.getOpeCode()))
                .map(ToolProductionCodeVO::getToolCode)
                .collect(Collectors.toList());
    }

    private static Map<String, Object> buildParamMap(List<String> eqptCodes, String opeCode, String paramCode,String startDate,String endDate,String ProdCode) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("EqptCodes", eqptCodes);
        paramMap.put("StartTime", startDate);
        paramMap.put("EndTime", endDate);
        paramMap.put("ProdCode", ProdCode);
        paramMap.put("opeCode", opeCode);
        paramMap.put("paramCode", paramCode);
        paramMap.put("SampleCount", 25);
        return paramMap;
    }

    public JsonNode makeApiCall(Map<String, Object> paramMap,String authorization) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost("http://172.16.34.71/api/spc-service/SPCService/GetStatisticData");
            httpPost.addHeader("Authorization", authorization);

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonParams = objectMapper.writeValueAsString(paramMap);
            HttpEntity entity = new org.apache.http.entity.StringEntity(jsonParams, org.apache.http.entity.ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entityResult = response.getEntity();
                if (entityResult!= null) {
                    String responseBody = EntityUtils.toString(entityResult);
                    ObjectMapper resultMapper = new ObjectMapper();
                    return resultMapper.readTree(responseBody).get("data");
                }
            } else {
                System.out.println("请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
